package com.taoz.taozrpc.springboot.starter.bootstrap;

import com.taoz.rpc.core.proxy.ServiceProxyFactory;
import com.taoz.taozrpc.springboot.starter.annotation.RpcClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

@Slf4j
public class RpcClientBootstrap implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        for (Field field : beanClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(RpcClient.class)) {
                Class<?> type = field.getType();
                field.setAccessible(true);
                try {
                    Object serviceProxy = ServiceProxyFactory.getServiceProxy(type);
                    field.set(bean, serviceProxy);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return bean;
    }
}
